<?php

class Controller_Insert
{
    protected $mapper = null;
    public $mesg = array();
    
    public function __construct()
    {
        require_once '../model/db.php';
        require_once '../model/entry.php';
        require_once '../model/mapper.php';
        
        // create instances
        $this->mapper = new MapperEntry();
    }
    
    private function _checkLastVisit($secToWait, $now) {
        if (isset($_SESSION["last_insert_time"])
            && ($now - $_SESSION["last_insert_time"]) < $secToWait) {
            return $secToWait - ($now - $_SESSION["last_insert_time"]);
        }
        return true;
    }
    
    public function index()
    {
        // time to lock the compose function in seconds
        $allow = self::_checkLastVisit(10, time());

        // check if user is allowed to write a new entry
        // $allow contains the seconds until a new post can be composed
        // 1 would be 1 sec left - so better use the === operator
        if ($allow === true) {
            // form was send
            if (isset($_POST["insert"])) {
                $name = trim($_POST["name"]);
                $text = nl2br(trim($_POST["entry"]));

                // check if fields are valid
                if (empty($name)) {
                    $this->mesg["err"][] = 'Please insert your name!';
                }
                if (empty($text)) {
                    $this->mesg["err"][] = 'Please insert some text!';
                }
                
                // no errors > insert into the database
                if (!isset($this->mesg["err"]) || empty($this->mesg["err"])) {
                    // inserts the data
                    if ($this->mapper->createEntry($name,$text)) {
                        $this->mesg["succ"][] = 'new entry was created!';
                        // save current time in a session
                        // to lock the compose function for a while for this user
                        $_SESSION["last_insert_time"] = time();
                    }
                }
            }
        } else {
            $this->mesg["err"][] = 'Please wait ' . $allow . ' seconds to compose a new entry!';
        }

        require_once '../view/header.php';
        require_once '../view/insert.php';
        require_once '../view/footer.php';
    }
}